package com.group.config;

import com.alibaba.fastjson.JSON;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.group.constants.UserConstants;
import com.group.entity.LoginUser;
import com.group.exception.IndustryException;
import com.group.utils.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token==null||token.equals("")) {
            filterChain.doFilter(request,response);
            return;
        }
        try {
            DecodedJWT verify = JWTUtils.verify(token);
            Map<String, String> userInfo = JWTUtils.getUserInfo(verify);
            if (userInfo==null) throw new IndustryException("身份验证错误");

            LoginUser userAccount = (LoginUser) redisTemplate.boundValueOps(UserConstants.USER_LOGIN_TOKEN + userInfo.get("userAccount")).get();
            if (userAccount==null){
                throw new IndustryException("身份验证错误");
            }
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(userAccount,null,userAccount.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(request,response);
        }catch (Exception e){
            e.printStackTrace();
            throw new IndustryException("无效的token");
        }
    }
}
